package zhishuang.wang.sansi.playlist.fcms;

import com.alibaba.fastjson.TypeReference;
import zhishuang.wang.sansi.playlist.AreaItem;
import zhishuang.wang.sansi.playlist.PageItem;
import zhishuang.wang.sansi.playlist.PlayItem;
import zhishuang.wang.sansi.playlist.entry.*;
import zhishuang.wang.sansi.tools.ReturnData;
import zhishuang.wang.sansi.tools.json.exception.FastjsonUtil;
import zhishuang.wang.sansi.tools.time.DateFormat;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Zhishuang.Wang
 * @Date 2023/7/5 11:11
 * @Email 1406110602@qq.com
 */

public class PlayListFcms {
    public PlayListFcms() {
    }

    public static ReturnData uploadCheckFileExist(String playJson, String fileDir) {
        ReturnData rd = new ReturnData();
        String errMessage = "";
        String materialName = "";
        String materialNamePath = "";
        List<String> resList = new ArrayList();

        try {
            PageItem pageItem = (PageItem) FastjsonUtil.from(playJson, new TypeReference<PageItem>() {
            });
            if (pageItem != null) {
                List<AreaItem> areaItemList = pageItem.getAreaItemList();

                for(int i = 0; i < areaItemList.size(); ++i) {
                    AreaItem areaItem = (AreaItem)areaItemList.get(i);
                    List<PlayItem> itemList = areaItem.getItemList();

                    for(int j = 0; j < itemList.size(); ++j) {
                        PlayItem playItem = (PlayItem)itemList.get(j);
                        if (playItem.getMaterialType() == 2) {
                            materialName = playItem.getPictureBase().getPicturePath();
                        } else if (playItem.getMaterialType() == 3) {
                            materialName = playItem.getVideoBase().getVideoPath();
                        } else {
                            materialName = "";
                        }

                        if (materialName != null && materialName.length() > 0) {
                            materialNamePath = fileDir + "/" + materialName;
                            File cFile = new File(materialNamePath);
                            if (!cFile.exists()) {
                                errMessage = errMessage + "素材文件：" + materialName + "  不存在；\n";
                            } else {
                                String[] nameArray = materialName.split("\\.");
                                String devFileName = "";
                                if (nameArray.length == 2) {
                                    String suffixName = nameArray[1];
                                    if (suffixName.equals("bmp")) {
                                        devFileName = "./bmp/" + materialName;
                                    } else if (suffixName.equals("jpg")) {
                                        devFileName = "./jpg/" + materialName;
                                    } else if (suffixName.equals("gif")) {
                                        devFileName = "./gif/" + materialName;
                                    } else if (suffixName.equals("mpg")) {
                                        devFileName = "./mpg/" + materialName;
                                    } else if (suffixName.equals("mp4")) {
                                        devFileName = "./mp4/" + materialName;
                                    } else if (suffixName.equals("png")) {
                                        devFileName = "./png/" + materialName;
                                    } else {
                                        devFileName = "./rds/" + materialName;
                                    }

                                    if (!resList.contains(devFileName)) {
                                        resList.add(materialNamePath);
                                        resList.add(devFileName);
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                errMessage = errMessage + "播放表文件异常\n";
            }
        } catch (Exception var18) {
            var18.printStackTrace();
            errMessage = errMessage + "播放表文件异常，请使用SDK生成\n";
        }

        if (errMessage != null && errMessage.length() != 0) {
            rd.setCode(1);
            rd.setMessage(errMessage);
        } else {
            rd.setCode(0);
            rd.setData(resList);
        }

        rd.setTime(DateFormat.getNowDataFormat());
        return rd;
    }

    private int calFcmsParamTime(Animation animation) {
        int speed = animation.getInAnimationSpeed();
        int param = speed / 20;
        if (speed % 20 != 0) {
            ++param;
        }

        if (param > 49) {
            param = 49;
        }

        return param;
    }

    private int animationToFcmsSwitch(Animation animation) {
        byte transition;
        switch (animation.getInAnimation()) {
            case 0:
                transition = 1;
                break;
            case 3:
                transition = 2;
                break;
            case 4:
                transition = 3;
                break;
            case 5:
                transition = 4;
                break;
            case 6:
                transition = 5;
                break;
            case 100:
                transition = 0;
                break;
            default:
                transition = 1;
        }

        return transition;
    }

    private int calFcmsDelayTime(PlayTimeBase playTime, int transition, int param, int width, int height) {
        int totalTime = playTime.getTotalTime();
        int speed = (param + 1) * 20;
        if (transition != 4 && transition != 5) {
            if (transition != 2 && transition != 3) {
                speed = 0;
            } else {
                speed *= height;
            }
        } else {
            speed *= width;
        }

        int delayTime = totalTime - speed;
        delayTime /= 10;
        return delayTime;
    }

    private String fcmsItemSet(PlayItem pItem, AreaPositon areaPositon, Background background) {
        String itemStr = "";
        Animation animation = pItem.getAnimation();
        PlayTimeBase playTime = pItem.getPlayTime();
        int transition = this.animationToFcmsSwitch(animation);
        int param = this.calFcmsParamTime(animation);
        int delay = this.calFcmsDelayTime(playTime, transition, param, areaPositon.getWidth(), areaPositon.getHeight());
        itemStr = delay + "," + transition + "," + param + ",";
        String videoName;
        if (pItem.getX() != null && pItem.getY() != null) {
            videoName = String.format("\\C%03d%03d", pItem.getX(), pItem.getY());
            itemStr = itemStr + videoName;
        }

        if (background != null && background.getBackColour() != null) {
            BaseColour baseColour = background.getBackColour();
            String backgroundStr = String.format("\\b%03d%03d%03d%03d", baseColour.getRed(), baseColour.getGreen(), baseColour.getBlue(), baseColour.getAmber());
            itemStr = itemStr + backgroundStr;
        }

        String suffixName;
        if (pItem.getMaterialType() == 1) {
            TextBase textBase = pItem.getTextBase();

            if (textBase.getFontName() != null) {
                suffixName = textBase.getFontSize();
                suffixName = suffixName.replaceAll(",", "");
                String fontStr = String.format("\\f%s%s", textBase.getFontName(), suffixName);
                itemStr = itemStr + fontStr;
            }

            BaseColour fontColour = textBase.getFontColour();
            if (fontColour != null) {
                suffixName = String.format("\\c%03d%03d%03d%03d", fontColour.getRed(), fontColour.getGreen(), fontColour.getBlue(), fontColour.getAmber());
                itemStr = itemStr + suffixName;
            }

            if (textBase.getWordSpace() != null) {
                suffixName = String.format("\\S%02d", textBase.getWordSpace());
                itemStr = itemStr + suffixName;
            }

            itemStr = itemStr + textBase.getTextPath();
        } else {
            String[] nameArray;
            if (pItem.getMaterialType() == 2) {
                videoName = pItem.getPictureBase().getPicturePath();
                nameArray = videoName.split("\\.");
                if (nameArray.length == 2) {
                    suffixName = nameArray[1];
                    if (suffixName.equals("bmp")) {
                        itemStr = itemStr + String.format("\\B%s", nameArray[0]);
                    } else if (suffixName.equals("jpg")) {
                        itemStr = itemStr + String.format("\\J%s", nameArray[0]);
                    } else if (suffixName.equals("gif")) {
                        itemStr = itemStr + String.format("\\G%s", nameArray[0]);
                    } else if (suffixName.equals("png")) {
                        itemStr = itemStr + String.format("\\P%s", nameArray[0]);
                    } else {
                        itemStr = itemStr + String.format("\\X%s", nameArray[0]);
                    }
                } else {
                    itemStr = itemStr + String.format("\\X%s", nameArray[0]);
                }
            } else if (pItem.getMaterialType() == 3) {
                videoName = pItem.getVideoBase().getVideoPath();
                nameArray = videoName.split(".");
                if (nameArray.length == 2) {
                    suffixName = nameArray[1];
                    if (suffixName.equals("mpg")) {
                        itemStr = itemStr + String.format("\\M%s", nameArray[0]);
                    } else if (suffixName.equals("mp4")) {
                        itemStr = itemStr + String.format("\\V%s", nameArray[0]);
                    } else {
                        itemStr = itemStr + String.format("\\X%s", nameArray[0]);
                    }
                } else {
                    itemStr = itemStr + String.format("\\X%s", nameArray[0]);
                }
            }
        }

        return itemStr;
    }

    private ReturnData checkFcmsPlayItemParam(PageItem pageItem, String fileDir) {
        ReturnData rd = new ReturnData();
        String errMessage = "";
        List<AreaItem> areaItemList = pageItem.getAreaItemList();

        for(int i = 0; i < areaItemList.size(); ++i) {
            AreaItem areaItem = (AreaItem)areaItemList.get(i);
            List<PlayItem> itemList = areaItem.getItemList();

            for(int j = 0; j < itemList.size(); ++j) {
                PlayItem playItem = (PlayItem)itemList.get(j);
                if (playItem.getPlayTime().getTotalTime() == null) {
                    errMessage = errMessage + "播放项错误信息：播放项ID：" + playItem.getId() + " 播放总时间必填；\n";
                } else {
                    int totalTime = playItem.getPlayTime().getTotalTime();
                    totalTime /= 10;
                    if (totalTime < 2 || totalTime > 30000) {
                        errMessage = errMessage + "播放项错误信息：播放项ID：" + playItem.getId() + " 播放总时间范围[2 - 30000]；\n";
                    }
                }

                if (playItem.getAnimation() == null) {
                    errMessage = errMessage + "播放项错误信息：播放项ID：" + playItem.getId() + " 入动画必填；\n";
                } else {
                    Animation animation = playItem.getAnimation();
                    if (animation.getInAnimation() != null && animation.getInAnimationSpeed() != null) {
                        switch (animation.getInAnimation()) {
                            case 0:
                            case 3:
                            case 4:
                            case 5:
                            case 6:
                            case 100:
                                break;
                            default:
                                errMessage = errMessage + "播放项错误信息：播放项ID：" + playItem.getId() + " 入动画值范围；[0,3,4,5,6,100]\n";
                        }
                    } else {
                        errMessage = errMessage + "播放项错误信息：播放项ID：" + playItem.getId() + " 入动画必填；\n";
                    }
                }

                String pCheckFile;
                if (playItem.getMaterialType() != 1) {
                    File pfile;
                    if (playItem.getMaterialType() == 2) {
                        PictureBase pictureBase = playItem.getPictureBase();
                        if (pictureBase.getPictureType() != 0) {
                            errMessage = errMessage + "播放项错误信息：播放项ID：" + playItem.getId() + " 图片类型只支持预置图片；\n";
                        } else {
                            pCheckFile = fileDir + "/" + pictureBase.getPicturePath();
                            pfile = new File(pCheckFile);
                            if (!pfile.exists()) {
                                errMessage = errMessage + "播放项错误信息：播放项ID：" + playItem.getId() + " 图片 " + pictureBase.getPicturePath() + " 不存在；\n";
                            }
                        }
                    } else if (playItem.getMaterialType() == 3) {
                        VideoBase videoBase = playItem.getVideoBase();
                        if (videoBase.getVideoType() == 0) {
                            errMessage = errMessage + "播放项错误信息：播放项ID：" + playItem.getId() + " 视频类型只支持预置图片；\n";
                        } else {
                            pCheckFile = fileDir + "/" + videoBase.getVideoPath();
                            pfile = new File(pCheckFile);
                            if (!pfile.exists()) {
                                errMessage = errMessage + "播放项错误信息：播放项ID：" + playItem.getId() + " 视频 " + videoBase.getVideoPath() + " 不存在；\n";
                            }
                        }
                    } else {
                        errMessage = errMessage + "播放项错误信息：播放项ID：" + playItem.getId() + " 不存在的素材类型；\n";
                    }
                } else {
                    TextBase textBase = playItem.getTextBase();
                    if (textBase.getWordSpace() != null) {
                        int workSpace = textBase.getWordSpace();
                        if (workSpace < -9 || workSpace > 99) {
                            errMessage = errMessage + "播放项错误信息：播放项ID：" + playItem.getId() + " 字间距范围：-9-99；\n";
                        }
                    }

                    if (textBase.getFontName() != null) {
                        pCheckFile = textBase.getFontName();
                        if (!"hksf".contains(pCheckFile)) {
                            errMessage = errMessage + "播放项错误信息：播放项ID：" + playItem.getId() + " 字体支持范围：h,k,s,f；\n";
                        }
                    }

                    if (textBase.getTextType() != 0) {
                        errMessage = errMessage + "播放项错误信息：播放项ID：" + playItem.getId() + " 文本类型只支持文字内容；\n";
                    }
                }
            }
        }

        if (errMessage.length() > 0) {
            rd.setCode(1);
            rd.setMessage(errMessage);
        } else {
            rd.setCode(0);
        }

        rd.setTime(DateFormat.getNowDataFormat());
        return rd;
    }

    public ReturnData createFcmsPlayList(String fileName, PageItem pageItem) {
        ReturnData rd = new ReturnData();
        rd.setCode(0);
        File file = new File(fileName);
        String fileDir = file.getParent();
        String tempFileName = file.getName();
        if (!tempFileName.equals("play.lst") && tempFileName.length() != 3) {
            rd.setCode(1);
            rd.setMessage("播放表名称必须：play.lst或由三个可见字符组成（例如：000、A00、z01等）");
            return rd;
        } else {
            ReturnData checkRd = pageItem.checkParam();
            if (checkRd.getCode() == 0) {
                checkRd = this.checkFcmsPlayItemParam(pageItem, fileDir);
                if (checkRd.getCode() == 0) {
                    if (file.exists()) {
                        rd.setCode(1);
                        rd.setMessage("播放表存储名称重复");
                    } else {
                        try {
                            BufferedWriter w = null;
                            OutputStreamWriter write = null;

                            try {
                                file.createNewFile();
                                write = new OutputStreamWriter(new FileOutputStream(file), "GBK");
                                w = new BufferedWriter(write);
                                w.write("[playlist]\r\n");
                                List<AreaItem> areaItemList = pageItem.getAreaItemList();
                                int windowNum = areaItemList.size();
                                String fcmsPlayStr = "nwindows=" + windowNum + "\r\n";
                                w.write(fcmsPlayStr);
                                int i = 0;

                                while(true) {
                                    if (i >= windowNum) {
                                        String planJson = FastjsonUtil.to(pageItem);
                                        planJson = ";" + planJson;
                                        w.write(planJson);
                                        break;
                                    }

                                    AreaItem aItem = (AreaItem)areaItemList.get(i);
                                    fcmsPlayStr = "windows" + i + "_x=" + aItem.getAreaPositon().getX() + "\r\n";
                                    w.write(fcmsPlayStr);
                                    fcmsPlayStr = "windows" + i + "_y=" + aItem.getAreaPositon().getY() + "\r\n";
                                    w.write(fcmsPlayStr);
                                    fcmsPlayStr = "windows" + i + "_w=" + aItem.getAreaPositon().getWidth() + "\r\n";
                                    w.write(fcmsPlayStr);
                                    fcmsPlayStr = "windows" + i + "_h=" + aItem.getAreaPositon().getHeight() + "\r\n";
                                    w.write(fcmsPlayStr);
                                    List<PlayItem> playItemList = aItem.getItemList();
                                    int playItemNum = playItemList.size();
                                    if (i > 0) {
                                        fcmsPlayStr = "windows" + i + "_item_no=" + playItemNum + "\r\n";
                                    } else {
                                        fcmsPlayStr = "item_no=" + playItemNum + "\r\n";
                                    }

                                    w.write(fcmsPlayStr);

                                    for(int j = 0; j < playItemNum; ++j) {
                                        PlayItem pItem = (PlayItem)playItemList.get(j);
                                        String fcmsItemStr = this.fcmsItemSet(pItem, aItem.getAreaPositon(), aItem.getBackground());
                                        fcmsItemStr = new String(fcmsItemStr.getBytes("GBK"), "GBK");
                                        if (i > 0) {
                                            fcmsPlayStr = "windows" + i + "_item" + j + "=" + fcmsItemStr + "\r\n";
                                        } else {
                                            fcmsPlayStr = "item" + j + "=" + fcmsItemStr + "\r\n";
                                        }

                                        w.write(fcmsPlayStr);
                                    }

                                    ++i;
                                }
                            } catch (IOException var20) {
                                var20.printStackTrace();
                                rd.setCode(1);
                                rd.setMessage("操作播放表文件异常");
                            }

                            if (w != null) {
                                w.close();
                            }

                            if (write != null) {
                                write.close();
                            }

                            if (rd.getCode() != 1) {
                                rd.setCode(0);
                                rd.setMessage("生成FCMS播放表成功");
                            }
                        } catch (Exception var21) {
                            var21.printStackTrace();
                            rd.setCode(1);
                            rd.setMessage("生成播放表异常");
                        }

                        if (rd.getCode() != 0) {
                            file.delete();
                        }
                    }
                } else {
                    rd.setCode(1);
                    rd.setMessage(checkRd.getMessage());
                }
            } else {
                rd.setCode(1);
                rd.setMessage(checkRd.getMessage());
            }

            rd.setTime(DateFormat.getNowDataFormat());
            return rd;
        }
    }
}
